package com.ruoyi.web.controller.api.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.RedisUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.detail.domain.SessionDetail;
import com.ruoyi.detail.service.impl.SessionDetailServiceImpl;
import com.ruoyi.session.service.impl.SessionServiceImpl;
import com.ruoyi.web.controller.api.dto.RequestPayload;

import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;

import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;


import java.util.*;




@Service

public class ApiService {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private RequestPayload payload;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private SessionDetailServiceImpl sessionDetailService;


    Map<String, Object> responseData = new HashMap<>();

    @Autowired
    private SessionServiceImpl sessionService;

     private static LoginUser user;
    /**
     * 调用外部 AI API 接口
     *
     * @param query 查询的文本
     * @return AjaxResult
     */
    @SneakyThrows
    public AjaxResult callExternalApi(String query) {
//        user = SecurityUtils.getLoginUser();
//        将用户的query存入session_detail表中
//        JsonNode session = getUserSession();

        //sessionId 动态获取当前的sessionId 这里仅做测试
        generateSessionDetail(1, query,1);

        String[] prompts = {"topic", "abstract", "keywords", "introduction", "content", "references"};
        String url = "http://localhost:7861/chat/knowledge_base_chat"; // 替换为实际接口的URL
        // 模型名字的设置来源于前端的下拉选项
        payload.setModelName("chatglm3-6b");
        payload.setKnowledgeBaseName("thesis");

        // 存储最终的返回内容


        StringBuilder sb = new StringBuilder();

        HttpEntity<RequestPayload> requestEntity;
        ResponseEntity<String> response;

        for (int i = 0; i < prompts.length; i++) {
            payload.setPromptName(prompts[i]);
//            System.out.println("Prompt: " + prompts[i]);

            // 设置当前的 query
            payload.setQuery(query);
            requestEntity = new HttpEntity<>(payload);

            // 发送 POST 请求
            response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);

            // 解析响应
            String responseBody = response.getBody();
            System.out.println("Response body: " + responseBody);
            String answer = null;
            // 去掉前缀 'data: '，提取有效的 JSON 部分
            if (responseBody != null && responseBody.startsWith("data:")) {
                responseBody = responseBody.substring(6); // 去除 'data: '
                // 假设响应是 JSON 格式，提取 "answer" 字段
                JsonNode responseJson = objectMapper.readTree(responseBody);
                answer = responseJson.path("answer").asText();
            }

            sb.append(answer);


            // 将每次请求的返回结果存储到 responseData 中
            responseData.put(prompts[i], answer);
            // 更新 query
            query = answer;

        }


//         将结果存入sessionDetail表中
        //sessionId 动态获取当前的sessionId 这里仅做测试
        Integer sessionId = generateSessionDetail(
                1,
                sb.toString(), -1);

        //         将结果缓存到Redis中，session_detail id作为key，responseData作为value
        redisUtil.set("session_detail_"+sessionId.toString() , responseData);

        sb.setLength(0);
        return new AjaxResult(200, "success", responseData);

    }

    /**
     * 获取当前用户的会话信息(聊天会话）
     * @return JsonNode
     * @throws JsonProcessingException
     */
    private JsonNode getUserSession() throws JsonProcessingException {
        AjaxResult ajaxResult = sessionService.selectHistorySession(user.getUserId().intValue());
        Object data = ajaxResult.get("data");
        JsonNode session = objectMapper.readTree(data.toString());
        return session;
    }

    /**
     * 生成一个session_detail
     */
    public Integer generateSessionDetail(Integer sessionId, String content, int label) {
        SessionDetail sd = new SessionDetail();
        sd.setSessionId(sessionId);
        sd.setContent(content);
        sd.setLabel(label);
      sessionDetailService.insertSessionDetail(sd);
        sessionId = sd.getId();
        return sessionId;

    }
}
